<template>
  <view class="container">
    <!-- 标签栏 -->
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabList" 
        :key="index"
        class="tab-item"
        :class="{ active: current === index }"
        @click="onTabChange(index)"
      >
        {{ tab.name }}
      </view>
    </view>
    
    <!-- 列表 -->
    <view class="booking-list" v-if="bookingList.length > 0">
      <view
        class="booking-item"
        v-for="item in bookingList"
        :key="item.booking_id"
        @click="goDetail(item.booking_id)"
      >
        <view class="booking-header">
          <text class="booking-title">保洁预约</text>
          <text class="status-tag" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </text>
        </view>
        
        <view class="booking-content">
          <view class="booking-row">
            <text class="label">预约单元:</text>
            <text class="value">{{ item.unit_info }}</text>
          </view>
          <view class="booking-row">
            <text class="label">预约日期:</text>
            <text class="value">{{ item.expected_service_date }}</text>
          </view>
          <view class="booking-row">
            <text class="label">预约时段:</text>
            <text class="value">{{ item.expected_time_slot }}</text>
          </view>
          <view class="booking-row">
            <text class="label">申请时间:</text>
            <text class="value">{{ formatDateTime(item.application_time) }}</text>
          </view>
        </view>
        
        <view class="booking-footer">
          <button
            v-if="item.status === 'completed' || item.status === '已完成'"
            class="btn btn-primary"
            size="mini"
            @click.stop="goRate(item.booking_id)"
          >评价</button>
          <button
            v-if="['pending', 'accepted', '待受理', '已受理'].includes(item.status)"
            class="btn btn-danger"
            size="mini"
            @click.stop="handleCancel(item)"
          >取消预约</button>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无保洁预约记录</text>
    </view>
    
    <!-- 底部添加按钮 -->
    <view class="add-btn-wrapper">
      <button class="add-btn" @click="goCreate">新增保洁预约</button>
    </view>
    
    <!-- 取消预约确认弹窗 -->
    <view v-if="showCancelConfirm" class="modal-mask">
      <view class="modal-content">
        <view class="modal-title">取消预约确认</view>
        <view class="modal-body">确定要取消该保洁预约吗？</view>
        <view class="modal-footer">
          <button class="modal-btn cancel-btn" @click="showCancelConfirm = false">取消</button>
          <button class="modal-btn confirm-btn" @click="confirmCancel">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCurrentUserCleaningBookings, cancelCleaningBooking } from '@/api/services'
import eventBus from '@/utils/eventBus.js'

export default {

  data() {
    return {
      tabList: [
        { name: '全部' },
        { name: '待受理' },
        { name: '已受理' },
        { name: '已完成' }
      ],
      current: 0,
      bookingList: [],
      status: '',
      selectedBooking: null,
      showCancelConfirm: false
    }
  },
  onLoad(options) {
    // 注册刷新事件监听器
    this.refreshEventHandler = () => {
      console.log('收到刷新保洁列表事件')
      this.loadBookingList()
    }
    eventBus.on('refreshCleaningList', this.refreshEventHandler)
    
    // 如果有refresh参数，则加载数据
    if (options && options.refresh === 'true') {
      this.loadBookingList()
    }
  },
  onShow() {
    // 检查用户登录状态和ID
    const userInfo = uni.getStorageSync('userInfo')
    const token = uni.getStorageSync('token')
    console.log('当前用户信息:', userInfo, '令牌:', token)
    
    this.loadBookingList()
  },
  onUnload() {
    // 页面卸载时移除事件监听器
    if (this.refreshEventHandler) {
      eventBus.off('refreshCleaningList', this.refreshEventHandler)
    }
  },
  methods: {
    onTabChange(index) {
      this.current = index
      
      // 根据选项卡设置筛选状态
      switch (index) {
        case 0:
          this.status = ''
          break
        case 1:
          this.status = '待受理'
          break
        case 2:
          this.status = '已受理'
          break
        case 3:
          this.status = '已完成'
          break
      }
      
      this.loadBookingList()
    },
    
    loadBookingList() {
      const params = {}
      if (this.status) {
        params.status = this.status
      }
      
      uni.showLoading({ title: '加载中...' })
      
      getCurrentUserCleaningBookings(params)
        .then(res => {
          console.log('获取保洁预约列表响应:', res) // 打印完整响应以便调试
          
          // 处理后端返回的数据格式
          if (res.code === 200 && res.data && res.data.list) {
            this.bookingList = res.data.list
          } else {
            this.bookingList = []
            uni.showToast({
              title: '暂无数据',
              icon: 'none'
            })
          }
        })
        .catch(err => {
          console.error('获取保洁预约列表失败:', err) // 打印错误信息
          this.bookingList = [] // 确保错误时列表为空
          
          // 改进错误处理，显示更具体的错误信息
          let errMsg = '未知错误'
          
          if (err && err.statusCode === 500) {
            errMsg = '服务器内部错误，请联系管理员'
          } else if (err && err.message) {
            errMsg = err.message
          } else if (typeof err === 'string') {
            errMsg = err
          }
          
          uni.showToast({
            title: `加载失败：${errMsg}`,
            icon: 'none',
            duration: 3000
          })
        })
        .finally(() => {
          uni.hideLoading()
        })
    },
    
    goDetail(id) {
      uni.navigateTo({
        url: `/pages/services/cleaning/detail?id=${id}`
      })
    },
    
    goCreate() {
      uni.navigateTo({
        url: '/pages/services/cleaning/create'
      })
    },
    
    goRate(id) {
      uni.navigateTo({
        url: `/pages/services/cleaning/rate?id=${id}`
      })
    },
    
    handleCancel(booking) {
      this.selectedBooking = booking
      this.showCancelConfirm = true
    },
    
    confirmCancel() {
      if (!this.selectedBooking) return
      
      uni.showLoading({ title: '取消中...' })
      
      cancelCleaningBooking(this.selectedBooking.booking_id)
        .then(() => {
          uni.showToast({
            title: '预约已取消',
            icon: 'success'
          })
          this.loadBookingList()
        })
        .catch(err => {
          uni.showToast({
            title: '取消失败：' + err.message,
            icon: 'none'
          })
        })
        .finally(() => {
          uni.hideLoading()
          this.selectedBooking = null
          this.showCancelConfirm = false
        })
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'pending': '待受理',
        'accepted': '已受理',
        'in_progress': '服务中',
        'completed': '已完成',
        'reviewed': '已评价',
        'cancelled': '已取消',
        // 添加中文状态映射，保持原样返回
        '待受理': '待受理',
        '已受理': '已受理',
        '服务中': '服务中',
        '已完成': '已完成',
        '已评价': '已评价',
        '已取消': '已取消'
      }
      return statusMap[status] || status
    },
    
    // 获取状态标签样式类
    getStatusClass(status) {
      const classMap = {
        // 英文状态
        'pending': 'status-warning',
        'accepted': 'status-primary',
        'in_progress': 'status-primary',
        'completed': 'status-success',
        'reviewed': 'status-success',
        'cancelled': 'status-danger',
        // 中文状态
        '待受理': 'status-warning',
        '已受理': 'status-primary',
        '服务中': 'status-primary',
        '已完成': 'status-success',
        '已评价': 'status-success',
        '已取消': 'status-danger'
      }
      return classMap[status] || 'status-primary'
    },
    
    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 120rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 标签栏样式 */
.tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
  padding: 15rpx 0;
}

.tab-item.active {
  color: #007aff;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #007aff;
  border-radius: 2rpx;
}

/* 列表样式 */
.booking-list {
  padding: 20rpx;
}

.booking-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.booking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f2f2f2;
  padding-bottom: 16rpx;
  margin-bottom: 16rpx;
}

.booking-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-tag {
  padding: 4rpx 12rpx;
  font-size: 24rpx;
  border-radius: 8rpx;
  color: #fff;
}

.status-primary {
  background-color: #007aff;
}

.status-success {
  background-color: #4cd964;
}

.status-warning {
  background-color: #f0ad4e;
}

.status-danger {
  background-color: #dd524d;
}

.booking-content {
  margin-bottom: 16rpx;
}

.booking-row {
  display: flex;
  margin-bottom: 10rpx;
}

.label {
  width: 180rpx;
  color: #666;
  font-size: 28rpx;
}

.value {
  flex: 1;
  color: #333;
  font-size: 28rpx;
}

.booking-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16rpx;
  border-top: 1px solid #f2f2f2;
}

/* 按钮样式 */
.btn {
  margin-left: 20rpx;
  font-size: 24rpx;
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  line-height: 1.5;
}

.btn-primary {
  background-color: #007aff;
  color: #fff;
}

.btn-danger {
  background-color: #dd524d;
  color: #fff;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

/* 添加按钮 */
.add-btn-wrapper {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
}

.add-btn {
  background-color: #007aff;
  color: #fff;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  font-size: 32rpx;
  width: 100%;
}

/* 取消预约确认弹窗样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 40rpx;
  border-radius: 12rpx;
  width: 80%;
  max-width: 600rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.modal-body {
  color: #666;
  font-size: 28rpx;
  margin-bottom: 40rpx;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
}

.modal-btn {
  margin-left: 20rpx;
  font-size: 24rpx;
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  line-height: 1.5;
}

.cancel-btn {
  background-color: #dd524d;
  color: #fff;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
}
</style> 